package edu.bw.controller.uoload;

import edu.bw.utils.ResponseData;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Log4j2
public class UploadController {
    private final String uploadPath = "E:\\JAVA代码\\java-EE\\day12-springmvc\\springmvc02\\src\\main\\webapp\\upload";

    @PostMapping("/single")
    public ResponseData singleUpload(@RequestParam("uploadFile") MultipartFile uploadFile) {
        if (uploadFile.isEmpty()) {
            return new ResponseData(400, "文件为空!");
        } else {
            try {
                uoloadFileToPath(uploadFile);
                return new ResponseData(200, "上传成功!");
            } catch (IOException e) {
                log.error("上传失败!", e);
                return new ResponseData(500, "上传失败!" + e.getMessage());
            }

        }

    }
    @PostMapping("/multiple")
    public ResponseData multipleUpload(@RequestParam("uploadFiles") MultipartFile[] uploadFiles) {
        if (uploadFiles.length == 0) {
            return new ResponseData(400, "文件为空!");
        } else {
            for (MultipartFile uploadFile : uploadFiles) {
                if (uploadFile.isEmpty()) {
                    return new ResponseData(400, "文件为空!");
                }

                try {
                    uoloadFileToPath(uploadFile);
                } catch (IOException e) {
                    log.error("上传失败!", e);
                    return new ResponseData(500, "上传失败!" + e.getMessage());
                }
            }
            return new ResponseData(200, "上传成功!");
        }
    }

    private void uoloadFileToPath(MultipartFile uploadFile) throws IOException {
        //获取文件全名
        String originalFilename = uploadFile.getOriginalFilename();
        //获取文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新文件名
        String newFileName = UUID.randomUUID().toString() + extension;
        //上传文件
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        File file = new File(uploadDir, newFileName);
        uploadFile.transferTo(file);
    }

}
